package com.mercury.base.converter;

import com.mercury.base.enums.base.IEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.lang.NonNull;


/**
 * 入参枚举转换器
 *
 * @author mercury
 */
public class IEnumConverterFactory implements ConverterFactory<String, IEnum> {

    @Override
    public <T extends IEnum> Converter<String, T> getConverter(@NonNull Class<T> targetType) {
        return new ValuedEnumConverter<>(targetType);
    }

    private static class ValuedEnumConverter<T extends IEnum> implements Converter<String, T> {

        private final T[] values;

        public static final String CODE_MATCHES = "[0-9]+";

        public ValuedEnumConverter(Class<T> targetType) {
            //获取类下的枚举常量
            values = targetType.getEnumConstants();
        }

        @Override
        public T convert(String source) {
            if (!source.isEmpty()) {
                //支持数字->枚举转换
                if (source.matches(CODE_MATCHES)) {
                    for (T t : values) {
                        if (t.getCode() == Integer.parseInt(source)) {
                            return t;
                        }
                    }
                } else {
                    //支持原来默认的字符串->枚举转换
                    for (T value : values) {
                        if (value.toString().equals(source)) {
                            return value;
                        }
                    }
                }
            }
            return null;
        }
    }
}

